#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""
import datetime
import os
import sys
import json
import requests
from elasticsearch import Elasticsearch
from pandas.io.json import json_normalize
import pandas as pd
import numpy as np

cur_dir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append("%s/.." % cur_dir)
import config

sys.path.append("%s/.." % cur_dir)
from res.lijiacai.utils import tool

es_cluster = config.es_cluster


class GetDataSet():
    def es_clinet(self):
        return Elasticsearch(hosts=es_cluster, port=None)

    def esDataToFrame(self, data):
        hits = data.get("hits", {}).get("hits", [])
        res = json_normalize(hits)
        res = res.drop(["_index", "_type", "_id", "_score"], axis=1)
        cols = res.columns.values.tolist()
        col_dict = {}
        for i in cols:
            col_dict[i] = i.replace("_source.", "")
        res.rename(col_dict, axis='columns', inplace=True)
        return res

    def getDataSet(self, index="order_predict_dataset_v1",
                   start_time="2020-05-20 10:46:50",
                   end_time="2020-05-25 10:46:50"):
        dsl = {'query':
            {
                "bool": {
                    'must': [{'range': {
                        'CURRENT_TIME': {'from': start_time, 'to': end_time}}}]
                }
            },
            'from': 0, 'size': 500000}
        es = self.es_clinet()
        res = es.search(index=index, body=json.dumps(dsl))
        # print(json.dumps(res, ensure_ascii=False))
        df = self.esDataToFrame(res)
        return df


class VehicleAvgTime():
    mapping = {"AFTER_STATION_ID": "AFTER_STATION_ID", "LICENSE": "LICENSE", "STATUS": "STATUS",
               "CURRENT_TIME": "CURRENT_TIME"}

    def __init__(self):
        self.data = None
        self.redis_client = tool.RedisDB(**config.redis_conf).client

    def init_data_es(self, index="order_predict_dataset_v1",
                     start_time="2020-04-20 10:46:50",
                     end_time="2020-05-25 10:46:50"):
        data = GetDataSet()
        data_ = data.getDataSet(index=index, start_time=start_time, end_time=end_time)
        res = data_[list(self.mapping)]
        res.rename(self.mapping, axis='columns', inplace=True)
        self.data = res

    def run(self):
        times = [[0, 3], [3, 6], [6, 9], [9, 12], [12, 15], [15, 18], [18, 21], [21, 24]]
        today = datetime.datetime.today()
        tomorrow = today + datetime.timedelta(days=1)
        start_time = today - datetime.timedelta(days=30)
        end_time = today
        self.init_data_es(index=config.vehicle_status_dataset,
                          start_time=str(start_time.date()) + " 00:00:00",
                          end_time=str(end_time.date()) + " 00:00:00")
        self.data["CURRENT_TIME"] = pd.to_datetime(self.data.CURRENT_TIME, format="%Y/%m/%d %H:%M:%S")
        data1 = self.data.shift(-1)
        data2 = self.data.shift(-2)
        data1.fillna("", inplace=True)
        data2.fillna("", inplace=True)
        return self.cal(self.data, data1, data2)

    def cal(self, data, data1, data2):
        out = {}
        for row1, row2, row3 in zip(data.iterrows(), data1.iterrows(), data2.iterrows()):
            if "空闲" in row1[1].STATUS and "已预订" in row2[1].STATUS and "已租" in row3[1].STATUS and row1[1].LICENSE == \
                    row2[1].LICENSE == row3[1].LICENSE:
                minites = (row3[1].CURRENT_TIME - row1[1].CURRENT_TIME).seconds / 60
                stationId = str(int(row1[1].AFTER_STATION_ID))
                orig = out.get(stationId, [0, 0])
                out[stationId] = [orig[0] + minites, orig[1] + 1]
        return out

    def go(self):
        res = self.run()
        self.redis_client.set("vehicle_avg_time_result", json.dumps(res), ex=None, px=None, nx=False, xx=False)


if __name__ == '__main__':
    VehicleAvgTime().go()
